package com.heima.wemedia.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    private String prefix;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Override
    public ResponseResult uploadPic(MultipartFile multipartFile) {
        // 1 参数校验,文件是否有效,检查图片格式,检查是否登录

        if (multipartFile.getSize()<=0||multipartFile==null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件不能为空");

        }
        String originalFilename = multipartFile.getOriginalFilename();
        // 截取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(!checkSuffix(suffix)){
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件格式不符合要求");

        }
        WmUser user = WmThreadLocalUtils.getUser();
        // 判断是否登录
        if(user==null){
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录后才能上传素材");
        }
        String fileName=null;
        try {
            // 将文件上传到oss,使用uuid生成新的文件
            //3 上传到oss得到文件路径,创建素材对象,设置文件路径,当前登录用户id
            //替换ssa-aad中的-
            String newFileName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
            // 上传oss,得到文件的oss路径
            fileName = fileStorageService.store(prefix, newFileName, multipartFile.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
            CustomException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传到oss失败");
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(fileName);
        wmMaterial.setUserId(user.getId());
        this.save(wmMaterial);

        //4 将素材对象回显给前端,保存完成,将素材url路径补全
        wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public PageResponseResult materialList(WmMaterialDTO dto) {
        // 1 参数校验
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录");
        }
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> wmMaterialPage = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> resultPage = this.page(wmMaterialPage, queryWrapper);
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }

        return new PageResponseResult(dto.getPage(),dto.getSize(),resultPage.getTotal(),records);
    }

    private boolean checkSuffix(String suffix) {

        if(StringUtils.isBlank(suffix)){
            return false;
        }
        List<String> allSuffix = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        boolean isCheck=false;
        for (String allow : allSuffix) {
            if (allow.equalsIgnoreCase(suffix)){
                isCheck =true;
                break;
            }
        }
        return isCheck;
    }
    @Autowired
    WmNewMaterialMapper wmNewMaterialMapper;
    @Override
    public ResponseResult deletePictureById(Integer id) {
        if (id==null){
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if(wmMaterial==null){
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);

        }
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery();
        //判断id是否被引用
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewMaterialMapper.selectCount(queryWrapper);
        if(count>0){
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        removeById(id);
        fileStorageService.delete(wmMaterial.getUrl());
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        WmMaterial material = getById(id);
        if (material == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if(!material.getUserId().equals(uid)){
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }
        material.setIsCollection(type);
        updateById(material);
//        update(Wrappers.<WmMaterial>lambdaUpdate()  // 如果只想修改指定字段 可以使用此方法
//                .set(WmMaterial::getIsCollection,type)
//                .eq(WmMaterial::getId,id)
//                .eq(WmMaterial::getUserId,uid));
        return ResponseResult.okResult();
    }
}
